// category.js
const { categories, blogPosts } = require('../../utils/data');
const app = getApp();

Page({
  data: {
    categories: [],
    selectedCategory: null,
    categoryPosts: [],
    t: {}, // Translations
    currentLanguage: 'en'
  },
  
  onLoad: function() {
    // Initialize translations
    this.loadLanguage();
    
    this.setData({
      categories
    });
  },
  
  // Load translations based on current language
  loadLanguage() {
    const i18n = app.globalData.i18n;
    const currentLanguage = i18n.getLanguage();
    
    // Create translations object
    const t = {
      allCategories: i18n.t('allCategories'),
      postsInCategory: i18n.t('postsInCategory'),
      backToCategories: i18n.t('backToCategories')
    };
    
    this.setData({
      t,
      currentLanguage
    });
  },
  
  // Handle language change event from navigation bar
  onLanguageChange(e) {
    const language = e.detail.language;
    app.globalData.i18n.setLanguage(language);
    this.loadLanguage();
  },
  
  onCategoryTap(e) {
    const categoryId = e.currentTarget.dataset.id;
    const selectedCategory = this.data.categories.find(cat => cat.id === categoryId);
    
    // Filter posts by category
    const categoryPosts = blogPosts.filter(post => post.category === selectedCategory.name);
    
    this.setData({
      selectedCategory,
      categoryPosts
    });
  },
  
  onPostTap(e) {
    const postId = e.detail.id;
    wx.navigateTo({
      url: `/pages/post-detail/post-detail?id=${postId}`
    });
  },
  
  onLikeTap(e) {
    const postId = e.detail.id;
    wx.showToast({
      title: `Liked post ${postId}`,
      icon: 'success'
    });
  },
  
  onBackTap() {
    // Clear the selected category to go back to the category grid
    this.setData({
      selectedCategory: null,
      categoryPosts: []
    });
  }
})